package com.alm.token.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.EggPartnerIndexData;
import com.alm.token.ui.data.bean.MioOperatorAddOrderData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.EggPartnerView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;

import java.util.ArrayList;
import java.util.List;

import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.alm.token.utils.CommonUtil.formatSeconds;

public class BuyEggPartnerActivity extends BaseActivity implements EggPartnerView<EggPartnerIndexData> {


    @BindView(R.id.tv_totalmoney)
    TextView tvTotalmoney;
    @BindView(R.id.img_selectbizhong)
    ImageView imgSelectbizhong;
    @BindView(R.id.ly_ooutmoneybizhongtop)
    RelativeLayout lyOoutmoneybizhongtop;
    @BindView(R.id.tv_getseth)
    TextView tvGetseth;
    @BindView(R.id.tv_buymsg)
    TextView tvBuymsg;
    @BindView(R.id.tv_buycommit)
    TextView tvBuycommit;
    @BindView(R.id.tv_smiototle)
    TextView tvSmiototle;
    @BindView(R.id.tv_mioblance)
    TextView tvMioblance;
    @BindView(R.id.tv_staue)
    TextView tvStaue;
    private List<EggPartnerIndexData.DataBean.GoodsBean> eggGoodsBeans = new ArrayList<>();
    private EggPartnerIndexData.DataBean dataBean;

    private int index = 0;

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_buyeggparter;
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void initViews() {
//        if (intentType == 1) {
        new ActionBarHelper(this).setTitle(getString(R.string.easteregg_hint_eggparnertitle));
//        tvBizhongtv.setText("");
        tvTotalmoney.setText("");
        imgSelectbizhong.setVisibility(View.INVISIBLE);
        tvGetseth.setText("");
        tvBuymsg.setText("");
    }

    @Override
    protected void loadData() {
        ShowProgress();
        preenter.getEggPartnerIndexData();
    }


    private CountDownTimer timer;
    private long times = 0, refreshTime = -1;

    private void initView() {
        /**
         * id : 1
         * price : 10000
         * totalNum : 3
         * remainNum : 3
         * getSmio : 10000
         * createTime : 1557196757000
         * updateTime : 1557198803000
         * status : 1
         * endTime : null
         * name : 10000
         * remark :
         */
        if (EmptyUtils.isNotEmpty(dataBean)) {
            tvSmiototle.setText(CommonUtil.saveToPoint4WithNo(dataBean.getRemainSMio()));
            tvMioblance.setText(CommonUtil.saveToPoint4WithNo(dataBean.getMio()));
            tvBuymsg.setText(EmptyUtils.isNotEmpty(dataBean.getMsg()) ? dataBean.getMsg() : "");
        }

        if (eggGoodsBeans.size() > 0) {
//            GlideApp.with(BuyEggPartnerActivity.this).load("").error(R.drawable.icon_arctic).into(imgBizhongicon);
            tvTotalmoney.setText(CommonUtil.saveToPoint4WithNo(eggGoodsBeans.get(index).getPrice()));
            imgSelectbizhong.setVisibility(eggGoodsBeans.size() > 1 ? View.VISIBLE : View.INVISIBLE);
//            tvGetseth.setText(getString(R.string.easteregg_hint_getegg1) + CommonUtil.saveToPoint4WithNo(eggGoodsBeans.get(index).getGetSmio()));
            tvGetseth.setText(CommonUtil.saveToPoint4WithNo(eggGoodsBeans.get(index).getGetSmio()));
            tvStaue.setText(eggGoodsBeans.get(index).getStatus() == 1 && eggGoodsBeans.get(index).getRemainNum() >= 1 ? getString(R.string.easteregg_hint_yes) : getString(R.string.easteregg_hint_no));
            times = eggGoodsBeans.get(index).getCountDown();

            if (times > 10) {
                refreshTime = times - 10;
            }
//                times = 100;
            if (EmptyUtils.isNotEmpty(timer)) {
                timer.cancel();
            }
            timer = new CountDownTimer(times * 1000, 1000) {
                /**
                 * 固定间隔被调用,就是每隔countDownInterval会回调一次方法onTick
                 * @param millisUntilFinished
                 */
                @Override
                public void onTick(long millisUntilFinished) {
                    if (millisUntilFinished / 1000 <= refreshTime && EmptyUtils.isNotEmpty(timer)) {
                        refreshTime = -1;
                        timer.onFinish();
//                        timer.cancel();
                    }
                    if (EmptyUtils.isNotEmpty(tvBuycommit)) {
                        tvBuycommit.setText(getString(R.string.easteregg_hint_partneropennexttime, formatSeconds(millisUntilFinished / 1000)));//结束倒计时
//                        tv_remaining_time.setText(formatTime(millisUntilFinished));
                    }
                }

                /**
                 * 倒计时完成时被调用
                 */
                @Override
                public void onFinish() {
                    if (EmptyUtils.isNotEmpty(preenter)) {
                        preenter.getEggPartnerIndexData();
                    }
//                        tv_remaining_time.setText("00:00");
                }
            };

            if (times != 0) {
                //"countDown": 86217, // 开启倒计时
                tvBuycommit.setText(getString(R.string.easteregg_hint_partneropennexttime, formatSeconds(times)));
                tvBuycommit.setOnClickListener(null);
                timer.start();
            } else {
                tvBuycommit.setText(getString(R.string.easteregg_hint_nowapply));
                tvBuycommit.setOnClickListener(this);
            }
        }

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.tv_buycommit:
                if (EmptyUtils.isNotEmpty(eggGoodsBeans) && eggGoodsBeans.size() > 0) {
                    UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                    sysMsgBean.setTitle(getString(R.string.common_warmprompt));
                    sysMsgBean.setContent(getString(R.string.common_warmprompt_isbuy));
                    DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {
                        preenter.getEggPartnerAddData(String.valueOf(eggGoodsBeans.get(index).getId()));
                    });
                } else {
                    showToast(getString(R.string.common_loaderrritry));
                    ShowProgress();
                    preenter.getEggPartnerIndexData();
                }
                break;
        }
    }


    @Override
    public void getData(EggPartnerIndexData eggPartnerIndexData) {
        if (eggPartnerIndexData.getStatus() == 0) {

            if (EmptyUtils.isNotEmpty(eggPartnerIndexData.getData())) {
                eggGoodsBeans = eggPartnerIndexData.getData().getGoods();
                dataBean = eggPartnerIndexData.getData();
                if (EmptyUtils.isNotEmpty(eggGoodsBeans) && eggGoodsBeans.size() > 0) {
                    initView();
                } else {
                    tvBuycommit.setText(getString(R.string.easteregg_hint_noopen));
                    tvBuycommit.setOnClickListener(null);
                }
            } else showToast(eggPartnerIndexData.getMsg());
        } else showToast(eggPartnerIndexData.getMsg());
    }

    @Override
    public void getEggPartnerAddData(RegisterData registerData) {
        showToast(registerData.getMsg());
        if (registerData.getStatus() == 0) {
            finish();
        }
    }

    @Override
    public void getMioOperatorAddOrderData(MioOperatorAddOrderData mioOperatorAddOrderData) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {

        hideWaitDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ly_ooutmoneybizhongtop})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.ly_ooutmoneybizhongtop:
                if (EmptyUtils.isNotEmpty(eggGoodsBeans) && eggGoodsBeans.size() > 0) {//升级超级vip不可选择
                    showPopupMenu(lyOoutmoneybizhongtop);
                } else {
                    ShowProgress();
                    preenter.getEggPartnerIndexData();
                }
                break;

        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (EmptyUtils.isNotEmpty(timer)) {
            timer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EmptyUtils.isNotEmpty(timer)) {
            timer.cancel();
            timer = null;
        }
    }

    public void showPopupMenu(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        for (EggPartnerIndexData.DataBean.GoodsBean eggGoodsBean : eggGoodsBeans) {
            menu.add(eggGoodsBean.getName());
        }
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);


        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                for (int i = 0; i < eggGoodsBeans.size(); i++) {
                    if (item.getTitle().toString().equalsIgnoreCase(eggGoodsBeans.get(i).getName())) {
                        if (index == i) {
//                            showToast(getString(R.string.crowdfund_hint_warn3));
                            break;
                        }
                        index = i;
                        if (EmptyUtils.isNotEmpty(preenter)) {
                            ShowProgress();
                            preenter.getEggPartnerIndexData();
                        }
//                        initView();
                        break;
                    }
                }
                return true;
            }
        });
        popupMenu.show();
    }


}
